import React, { Component } from 'react';
import { Icon, Upload, Modal, message } from 'antd';
import PropTypes from 'prop-types';
import ReactImageCrop from './ReactImageCrop';
import { data2blob } from '@/utils/common';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

class ReactImageCropUpload extends Component {
  static defaultProps = {
    // 上传接口地址，如果为空，图片不会上传
    url: '',
    // 上传方法
    method: 'POST',
    // 向服务器上传的文件名
    field: 'upload',
    // 上传附带其他数据，格式 {k:v}
    params: null,
    // 上传header设置，格式 {k:v}
    headers: null,
    // 支持跨域
    withCredentials: false,
    // 原名key，类似于id，触发事件会带上（如果一个页面多个图片上传控件，可以做区分
    ki: 0,
  };

  static propTypes = {
    url: PropTypes.string,
    method: PropTypes.string,
    field: PropTypes.string,
    params: PropTypes.object,
    headers: PropTypes.object,
    withCredentials: PropTypes.bool,
    ki: PropTypes.number,
    // handleCropUploadSuccess: PropTypes.func.isRequired,
    // handleCropUploadFail: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.cropRef = React.createRef();
    this.state = {
      visible: false,
    }
  }

  // 上传图片
  upload = ({ createImgUrl, blob, file }) => {
    const child = this.cropRef.current;
    const { url, params, headers, field, withCredentials, method, handleCropUploadSuccess, handleCropUploadFail, ki } = this.props;
    const { imgFormat } = child.state;
    const fmData = new FormData();
    fmData.append(field, data2blob(createImgUrl), field + "." + imgFormat);

    // 添加其他参数
    if (typeof params === 'object' && params) {
      Object.keys(params).forEach(k => {
        fmData.append(k, params[k]);
      });
    }

    // 监听进度回调
    // const uploadProgress = function(event) {
    //   if (event.lengthComputable) {
    //     that.progress = 100 * Math.round(event.loaded) / event.total;
    //   }
    // };
    // 上传文件
    // child.setStep(3);
    new Promise(function(resolve, reject) {
      let client = new XMLHttpRequest();
      client.open(method, url, true);
      client.withCredentials = withCredentials;
      client.onreadystatechange = function() {
        if (this.readyState !== 4) {
          return;
        }
        if (this.status === 200 || this.status === 201) {
          resolve(JSON.parse(this.responseText));
        } else {
          reject(this.status);
        }
      };
      // client.upload.addEventListener("progress", uploadProgress, false); //监听进度
      // 设置header
      if (typeof headers === 'object' && headers) {
        Object.keys(headers).forEach(k => {
          client.setRequestHeader(k, headers[k]);
        });
      }
      client.send(fmData);
    }).then(
      // 上传成功
      function(resData) {
        handleCropUploadSuccess(resData, field, ki);
      },
      // 上传失败
      function(sts) {
        handleCropUploadFail(sts, field, ki);
      },
    );
  };

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        }),
      );
    }
  };

  beforeUpload = (file) => {
    const imageType = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
    const isImage = imageType.findIndex(o => o === file.type) !== -1;
    if (!isImage) {
      message.error('请选择正确的图片类型!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2M!');
      return false;
    }

    let reader = new FileReader();
    reader.readAsDataURL(file);
    let _this = this;
    reader.onload = (e) => {
      _this.setState({
        cropSrc: e.target.result,
        visible: true,
      })
    }
    return new Promise((resolve, reject) => {
      let index = setInterval(() => {
        if (this.blob) { // 监听裁剪是否完成
          window.clearInterval(index);
          this.blob.uid = file.uid; // 需要给裁剪后的blob对象设置uid，否则会报错！！！
          resolve(this.blob); // 执行后续的上传操作
        }
      },300);
    });
  };

  render() {
    const { imageUrl, visible } = this.state;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div>
        <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          beforeUpload={this.beforeUpload}
          onChange={this.handleChange}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
        <Modal title="头像裁剪" visible={visible}>
          <ReactImageCrop {...this.props} upload={this.upload} ref={this.cropRef} />
        </Modal>
      </div>
    );
  }
}

export default ReactImageCropUpload;
